package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.LastRecord;
import com.xiaocz.hblsubstitutedriving.model.Reason;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.widget.ClearTextIconEditText;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2019/7/23
 * Created by xiaocz
 * Describe 提现
 */
public class WithdrawDepositActivity extends BaseActivity {


    public static void show(Context context) {
        Intent intent = new Intent(context, WithdrawDepositActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.ed_name)
    TextView edName;
    @BindView(R.id.tv_opening_bank)
    TextView tvOpeningBank;
    @BindView(R.id.ed_card_id)
    ClearTextIconEditText edCardId;
    @BindView(R.id.ed_money)
    ClearTextIconEditText edMoney;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.ed_pwd)
    ClearTextIconEditText edPwd;


    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_withdraw_deposit;
    }

    @Override
    protected void initData() {
        UserInfo info = new Gson().fromJson(AccountManagers.getAccount(), UserInfo.class);
        if (info != null) {
            edName.setText(info.getTruename());
        }
        webWithdrawalHistory();
        super.initData();

        edMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
                String textValue = text.toString().trim();
                if(textValue.length()>0){
                    if(txDecimal.subtract(new BigDecimal(textValue)).doubleValue()<0){
                        textValue=textValue.substring(0,textValue.length()>1?textValue.length()-1:textValue.length());
                        edMoney.setText(textValue);
                        edMoney.setSelection(textValue.length()); //光标移动到最后
                        App.getInstance().showMessage("已超过可提现金额！");
                        return;
                    }
                }
                edMoney.onTextChanged(text, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({R.id.tv_opening_bank, R.id.btn_withdraw_deposit, R.id.btn_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_opening_bank://银行卡选择
                webExtraChargesList();
                break;
            case R.id.btn_withdraw_deposit://提现列表
                TiXianListActivity.show(mContext);
                break;
            case R.id.btn_submit://提现申请
                isCheckValue();
                break;
        }
    }

    /**
     * 数据效验
     */
    private void isCheckValue() {
        if (TextUtils.isEmpty(edName.getText())) {
            App.getInstance().showMessage("请输入提现人姓名！");
            return;
        }
        if (TextUtils.isEmpty(tvOpeningBank.getText())) {
            App.getInstance().showMessage("请选择提现银行！");
            return;
        }
        if (TextUtils.isEmpty(edCardId.getText())) {
            App.getInstance().showMessage("请输入银行卡号！");
            return;
        }
        if (TextUtils.isEmpty(edMoney.getText())) {
            App.getInstance().showMessage("请输入提现金额！");
            return;
        }
        if (TextUtils.isEmpty(edPwd.getText())) {
            App.getInstance().showMessage("请输入提现密码！");
            return;
        }
        webAddWithdrawDeposit(edName.getText().toString(), tvOpeningBank.getText().toString(), edCardId.getText().toString(), edMoney.getText().toString(), edPwd.getText().toString());
    }

    BigDecimal txDecimal=new BigDecimal("0");
    /**
     * 上一次提现记录
     */
    private void showLastRecord(LastRecord record){
        if(record.getBankname()!=null && !"".equals(record.getBankname())){
            edName.setText(record.getTruename());
        }
        tvOpeningBank.setText(record.getBankname());
        edCardId.setText(record.getCardNo());
        txDecimal=record.getBalance().subtract(record.getDeposit());
        edMoney.setHint(String.format("可提现金额%s元",txDecimal));
        tvMoney.setVisibility(View.VISIBLE);
        StringBuilder builder=new StringBuilder();
        builder.append(String.format("2.剩余%s元账户保底金额，办理完全解除其合作关系时无违规和待处理的客户投诉情况下一次全提;",record.getDeposit()));
        if(record.getVat()!=0){
            builder.append(String.format("\n3.根据国家有关规定，代驾收入属于个体经营所得，应缴纳个人所得税和增值税，增值税率%s%%个人所得税率%s%%;",record.getVat(),record.getPit()));
        }
        tvMoney.setText(builder.toString());

    }

    /**
     * 获取上一次提现信息
     */
    private void webWithdrawalHistory() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        okHttpClient.post(Common.Constant.API_IP + "api/TiXian/QueryLastTiXianOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<LastRecord>>() {
                }.getType();
                RspModel<LastRecord> rspModel = getAnalysis(response, type, "获取上一次提现信息");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            if(rspModel.getData() != null){
                                showLastRecord(rspModel.getData());
                            }
                        }else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 获取提现银行卡列表
     */
    private void webExtraChargesList() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("chosetype_id", "5");
        okHttpClient.post(Common.Constant.API_IP + "api/Order/ChoseContentList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<List<Reason>>>() {
                }.getType();
                RspModel<List<Reason>> rspModel = getAnalysis(response, type, "获取提现银行卡列表");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            dialogBankName(rspModel.getData());
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 显示银行卡
     */
    private void dialogBankName(List<Reason> reasonList) {
        final String[] cancelReason = new String[reasonList.size()];
        for (int i = 0; i < reasonList.size(); i++) {
            cancelReason[i] = reasonList.get(i).getContent();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择提现银行");
        builder.setItems(cancelReason, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tvOpeningBank.setText(cancelReason[which]);
            }
        });
        builder.show();
    }

    /**
     * 提现申请
     */
    private void webAddWithdrawDeposit(String trueName, String bankName, String cardNo, String money, String pwd) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("truename", trueName);
        asyncHttpPostFormData.addFormData("bankname", bankName);
        asyncHttpPostFormData.addFormData("cardNo", cardNo);
        asyncHttpPostFormData.addFormData("money", money);
        asyncHttpPostFormData.addFormData("pwd", pwd);
        okHttpClient.post(Common.Constant.API_IP + "api/TiXian/CreateTiXianOrderNoCard", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "提现申请");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        App.getInstance().showMessage(rspModel.getMessage());
                        if (rspModel.isStatus()) {
                            Intent intent = new Intent();
                            setResult(2, intent);
                            finish();
                        }else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }
}
